<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchCustomerServiceListAPI } from '@/apis/fetchCustomerServiceList'
import { useUserInfoStore } from '@/store/userInfo'
import type { CustomerServiceListItem, LoadMoreData } from '@/types/api'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<CustomerServiceListItem>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<CustomerServiceListItem>): Promise<LoadMoreData<CustomerServiceListItem>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchCustomerServiceListAPI(
    { page: _page.toString(), limit: '10' },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleTapItem(id: string) {
  router.push({
    name: 'customerServiceDetail',
    params: { id },
  })
}
</script>

<template>
  <Spacer height="30" />
  <view class="mx-24rpx rounded-20rpx bg-white">
    <block v-for="item, index in dataList" :key="item.id">
      <view class="px-30rpx py-40rpx" @tap="handleTapItem(item.id.toString())">
        <view class="text-32rpx text-#333333 font-bold leading-45rpx">
          {{ item.title }}
        </view>
        <Spacer height="24rpx" />
        <view class="text-28rpx text-#999999 font-medium leading-40rpx">
          {{ item.introduce }}
        </view>
      </view>
      <Divider v-if="index !== dataList.length - 1" width="642" />
    </block>
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </view>
  <Spacer height="180" />
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'customerServiceCenter'
style:
  navigationBarTitleText: '客服中心'
</route>
